package com.xin.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xin.entity.*;
import com.xin.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * created by l1 on 2017/12/20.
 */
@Controller
@RequestMapping("/admin")
public class TeacherManagerController{

    @Autowired
    private UTeacherInfoService uTeacherInfoService;

    @Autowired
    private STeacherRoleService sTeacherRoleService;

    @Autowired
    private SOrgService sOrgService;

    @Autowired
    private SRoleOrgService sRoleOrgService;

    @Autowired
    private STeacherRoleRelationService sTeacherRoleRelationService;


    @GetMapping("/roleList")
    public String roleList(){
        return "roleList";
    }
    @RequestMapping("/roleManagement")
    public String roleManagement(String account_id,HttpServletRequest request){
        HttpSession session = request.getSession(true);
        UTeacherInfo utInfo = (UTeacherInfo) session.getAttribute("utInfo");
        String id = (String)session.getAttribute("id");

        if(id == null ){
            utInfo = uTeacherInfoService.selectById(account_id);
            session.setAttribute("id",utInfo.getId());
            session.setAttribute("name",utInfo.getName());
            session.setAttribute("utInfo",utInfo);
        }
        return "roleManagement";
    }
    @GetMapping("/loadOrgs")
    public String loadOrgs(){
        return "addRole";
    }

    @PostMapping("/queryRoles")
    @ResponseBody
    public JSONObject roleList(Integer pageNum,Model model){
        JSONObject result = new JSONObject();
        if(pageNum == null) {
            pageNum = 1;
        }
        // 查看角色列表
        Page<STeacherRole> rolePages = sTeacherRoleService.selectPage(new Page<STeacherRole>(pageNum,15));
        result.put("rolePages",rolePages);
        result.put("pageNum",pageNum);
        result.put("total",rolePages.getTotal());
        result.put("pages",rolePages.getPages());
        result.put("list",rolePages.getRecords());
        //计算开始 结束
        int start = pageNum-4;
        int end = pageNum+5;
        if(end<=rolePages.getPages()){
            result.put("end",end);
            if(start>0){
                result.put("start",start);
            }else {
                result.put("start",1);
            }
        }else {
            result.put("end",rolePages.getPages());
            if(start>0){
                result.put("start",start);
            }else {
                result.put("start",1);
            }
        }

        return result;
    }

//    @GetMapping("/addRole")
//    @ResponseBody
//    public String listRole(Model model){
//        //查询所有角色
//       JSONArray trees = sOrgService.getTrees(null);
//        model.addAttribute("trees",trees);
//
//        return "/addRole";
//    }

    @GetMapping("/getOrgList")
    @ResponseBody
    public JSONArray getOrgList(){
        return sOrgService.getTrees(null);
    }

    @PostMapping(value = "/addRole",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public JSONObject addRole(@RequestBody  JSONObject param){
        JSONObject result = new JSONObject();
        String roleName = param.getString("roleName");
        JSONArray nodesArray = param.getJSONArray("nodesArray");
        STeacherRole str = new STeacherRole();
        str.setRoleName(roleName);
        //判断角色是否存在
        int count = sTeacherRoleService.selectCount(new EntityWrapper<>(str));
        if(count>0){
            result.put("test","test");
            result.put("status",false);
            result.put("message","该角色名称已存在!");
        }else {
            result.put("test","test");
            result.put("status",true);
            result.put("message","成功");
            sTeacherRoleService.insert(str);
            sRoleOrgService.addRoleAndOrgs(str,nodesArray);
        }
        return result;
    }
    @GetMapping("/editRoleList/{roleId}")
    public String editRole(Model model,@PathVariable("roleId") Integer roleId){
        STeacherRole sTeacherRole = sTeacherRoleService.selectById(roleId);
        model.addAttribute("roleId",roleId);
        model.addAttribute("roleName",sTeacherRole.getRoleName());
        return "editRole";
    }
    @GetMapping("/getOrgListByRoleId")
    @ResponseBody
    public JSONArray getOrgList(Integer roleId){
        List<SRoleOrg> roleOrgs = sRoleOrgService.selectList(new EntityWrapper<SRoleOrg>().eq("role_id", roleId));
        List<Integer> orges = new ArrayList<>();
        roleOrgs.forEach(sRoleOrg -> {
            orges.add(sRoleOrg.getOrgId());
            SOrg sOrg = sOrgService.selectById(sRoleOrg.getOrgId());
            if(sOrg.getLevel() == 1){
                List<SOrg> children = sOrgService.selectList(new EntityWrapper<SOrg>().eq("parent_id", sOrg.getId()));
                children.forEach(child->{
                    if(!orges.contains(child.getId())){
                        orges.add(child.getId());
                    }
                });
            }else if(!orges.contains(sOrg.getParentId()) && sOrg.getLevel()!=1){
                orges.add(sOrg.getParentId());
            }
        });
        return sOrgService.getTrees(orges);
    }

    @PostMapping(value = "/editRole",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public JSONObject editRole(@RequestBody  JSONObject param){
        JSONObject result = new JSONObject();
        String roleName = param.getString("roleName");
        Integer roleId = param.getInteger("roleId");
        JSONArray nodesArray = param.getJSONArray("nodesArray");
        STeacherRole str = new STeacherRole();
        str.setRoleName(roleName);
        //判断角色是否存在
        int count = sTeacherRoleService.selectCount(new EntityWrapper<>(str).ne("id",roleId));
        if(count>0){
            result.put("test","test");
            result.put("status",false);
            result.put("message","该角色名称已存在!");
        }else {
            result.put("test","test");
            result.put("status",true);
            result.put("message","成功");
            str.setId(roleId);
            sRoleOrgService.editRoleAndOrgs(str,nodesArray);
        }
        return result;
    }


    @GetMapping("/role/delete/{roleId}")
    @ResponseBody
    public JSONObject roleDelete(@PathVariable("roleId") Integer roleId){
        System.out.println("delete....:"+roleId);

        sTeacherRoleRelationService.delete(new EntityWrapper<STeacherRoleRelation>().eq("role_id",roleId));
        sRoleOrgService.delete(new EntityWrapper<SRoleOrg>().eq("role_id",roleId));
        sTeacherRoleService.deleteById(roleId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status",true);
        return jsonObject;
    }
    @RequestMapping("/roleConfigure")
    public String roleConfigure(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        UTeacherInfo utInfo = (UTeacherInfo) session.getAttribute("utInfo");
        String id = (String)session.getAttribute("id");

        return "roleConfigure";
    }

    @GetMapping("/initRoleList")
    @ResponseBody
    public JSONArray initRoleList(){
        return sTeacherRoleService.initRoleList();
    }

    @PostMapping("/roleQuery")
    @ResponseBody
    public JSONObject roleQuery(String roleId,String name,String eid,String cid,Integer pageSize,Integer pageNum){
        return sTeacherRoleRelationService.query(roleId,name,eid,cid,pageSize,pageNum);
    }

    @RequestMapping("/modifyRole")
    public String modifyRole(Model model,String eid){
        List<JSONObject> roles = sTeacherRoleRelationService.queryRoles(eid);
        model.addAttribute("roles",roles);
        model.addAttribute("eid",eid);
        return "modifyRole";
    }

    @PostMapping("/modifyRoleByTeacher")
    @ResponseBody
    public JSONObject modifyRoleByTeacher(String roleId,String eid,HttpServletRequest request){
        JSONObject result = new JSONObject();
        sTeacherRoleRelationService.updateRelation(eid,roleId);
        return result;
    }
}
